import axios from 'axios'
import UserToken from '../api/user_token'
import {jsonToFormData, isEmptyObject} from '../common/vue-expand-func'
import {profile} from '../config/base'

const Method = {
  GET: 'GET',
  POST: 'POST'
}

const ReqContentType = {
  APPLICATION_JSON: 'application/json;charset=UTF-8',
  APPLICATION_FORM: 'application/x-www-form-urlencoded;charset=UTF-8'
}

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest' //设置该请求头用于服务器判断是否Ajax请求

/**
 * 请求前配置
 */
axios.interceptors.request.use((config) => { //请求操作
  let token = UserToken.getUserToken()
  if (token) {
    config.headers['Authorization'] = token
  }

  if (config.method === 'post') {
    if (config.data instanceof Object) { //如果传进来的是一个对象
      let params = ''
      for (let k in config.data) {
        params += `&${k}=${config.data[k]}`
      }
      config.data = params
    }
  }
  return config
}, (error) => {
  console.log('错误的传参', 'fail')
  return Promise.reject(error)
})

/**
 * 响应配置
 */
axios.interceptors.response.use((response) => {
  if (response.data) {
    return response.data
  }
  return response
}, (error) => {
  switch (error.response.status) {
    case 401:
      /** 无权限访问，去登录 **/
      UserToken.clearCookie()
      break
    case 500:
      if (typeof error.response.data.code !== 'undefined') {
        return error.response.data
      }
      break
  }
})

export default axios

export function ajax (url = '', data = {}, method = Method.GET, contentType = ReqContentType.APPLICATION_FORM) {
  return new Promise(function (resolve, reject) {
    let axiosRes
    switch (method) {
      case 'GET':
        let subffix=isEmptyObject(data) ? '' : '?' + jsonToFormData(data)
        axiosRes = axios.get(url + subffix)
        break
      case 'POST':
        axiosRes = axios({
          url: url,
          method: 'post',
          headers: {
            'Content-Type': contentType
          },
          data: contentType === ReqContentType.APPLICATION_FORM ? jsonToFormData(data) : JSON.stringify(data)
        })
        break
    }
    axiosRes.then(response => {
      resolve(response)
    }).catch(error => {
      reject(error);
    });
  });
}

let BASE_URL = profile.apiHost
export {Method,BASE_URL,ReqContentType}
